//
//  HomeHotFlowLayout.m
//  MissMeetLive
//
//  Created by Rowling on 2020/4/30.
//  Copyright © 2020 智码优服. All rights reserved.
//

#import "HomeHotFlowLayout.h"
@interface HomeHotFlowLayout()
@property(nonatomic,strong)NSMutableArray * attributeArray;
@property(nonatomic,assign)CGFloat  leftLastY;
@property(nonatomic,assign)CGFloat  rightLastY;

@end

@implementation HomeHotFlowLayout
-(void)prepareLayout {
    [super prepareLayout];
    self.attributeArray = [NSMutableArray array];
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    _leftLastY =  self.sectionInset.top;
    _rightLastY =  self.sectionInset.top;

    for (int i = 0; i < count; i++) {
        bool isLeft = i % 2 == 0;
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        UICollectionViewLayoutAttributes * atrri = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        CGSize size = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        CGFloat x = self.sectionInset.left;
        CGFloat y = 0;
        CGFloat lineSpace = 0;
        if (i > 1) {
            lineSpace = self.minimumLineSpacing;
        }
        if (isLeft) {
            // 左边
            y = _leftLastY + lineSpace;
            _leftLastY = y + size.height;
        } else {
            // 右边
            y = _rightLastY + lineSpace;
            x += (size.width + self.minimumInteritemSpacing);
            _rightLastY = y + size.height;
        }
        atrri.frame = CGRectMake(x, y, size.width, size.height);
        [self.attributeArray addObject:atrri];
    }
}

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attributeArray;
}

-(CGSize)collectionViewContentSize {
    CGFloat height = self.rightLastY > self.leftLastY ? self.rightLastY : self.leftLastY;
    CGFloat realHeight = height + self.sectionInset.bottom;
    if ([self.delegate respondsToSelector:@selector(minContentHeight)]) {
        CGFloat minHeigt = [self.delegate minContentHeight];
        if (realHeight < minHeigt) {
            realHeight = minHeigt;
        }
    }
    return  CGSizeMake(self.collectionView.frame.size.width,realHeight);
}

@end
